﻿using Microsoft.AspNetCore.Components;
using MudBlazor;
using SageKing.Designer.Core.Contexts;
using SageKing.Designer.Core.Contracts;
using SageKing.Designer.Core.Domain.Services;
using SageKing.Designer.Core.Enums;
using SageKing.Designer.Core.Models;
using SageKing.Designer.Core.UI.Args;
using SageKing.Designer.Core.UI.Contexts;
using SageKing.Designer.Core.UI.Contracts;
using SageKing.Designer.Core.UI.Models;
using System.Text.Json.Nodes;

namespace SageKing.Studio.Pages.Dashboard.Components;

public partial class ActivityPropertiesPanel
{
    /// <summary>
    /// Gets or sets the workflow definition.
    /// </summary>
    [Parameter]
    public WorkflowDefinition? WorkflowDefinition { get; set; }

    /// <summary>
    /// Gets or sets the activity.
    /// </summary>
    [Parameter]
    public JsonObject? Activity { get; set; }

    /// <summary>
    /// Gets or sets the activity descriptor.
    /// </summary>
    [Parameter]
    public ActivityDescriptor? ActivityDescriptor { get; set; }

    /// <summary>
    /// Gets or sets a callback that is invoked when the activity is updated.
    /// </summary>
    [Parameter]
    public Func<JsonObject, Task>? OnActivityUpdated { get; set; }

    /// <summary>
    /// Gets or sets the visible pane height.
    /// </summary>
    [Parameter]
    public int VisiblePaneHeight { get; set; }

    [Inject] private IExpressionService ExpressionService { get; set; } = default!;

    [Inject] private IEnumerable<IActivityTab> PluginTabs { get; set; } = new List<IActivityTab>();

    private ExpressionDescriptorProvider ExpressionDescriptorProvider { get; } = new();

    [CascadingParameter]
    public Error? Error { get; set; }
    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        try
        {
            var descriptors = await ExpressionService.ListDescriptorsAsync();
            ExpressionDescriptorProvider.AddRange(descriptors);
        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }
    }

    private bool IsWorkflowAsActivity => ActivityDescriptor != null && ActivityDescriptor.CustomProperties.TryGetValue("RootType", out var value) && value.ConvertTo<string>() == "WorkflowDefinitionActivity";
    private bool IsTaskActivity => ActivityDescriptor?.Kind == ActivityKind.Task;
}
